<template>
    <div class="body1">
        <div class="no-print el-button-print">
            <el-button @click="addForm">添加页</el-button>
            <el-button @click="deleteForm">删除页</el-button>
            <el-button @click="exportPDF">导出为pdf</el-button>
        </div>
        <div class="body2" id="pdfDom" :class="{ 'pdf-export': isPdfExport }">
            <div class="title">
                <div class="biaotididian">{{ agencyName }}</div>
                <div class="biaoti">现场检查（勘验）笔录</div>
            </div>
            <div class="tableStyle1">
                <!-- 主体-->
                <div class="writ-height">
                    <span>检查（勘验）时间：</span>
                    <editable-textarea :text="form.date1" param-type="YYYYMMDD1"
                        @send-to-parent="receiveFromChild"></editable-textarea>
                    <editable-textarea :text="form.time1" param-type="HH:mm1"
                        @send-to-parent="receiveFromChild"></editable-textarea>
                    <span>至</span>
                    <editable-textarea :text="form.time2" param-type="HH:mm2"
                        @send-to-parent="receiveFromChild"></editable-textarea>
                </div>
                <div class="writ-height">
                    <span>检查（勘验）地点：</span>
                    <input v-model="form.a1" :resize="'none'" autosize maxlength="23" class="inputStyle1"
                        style="width: calc(23 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea">
                </div>
                <div class="writ-height" style="margin-bottom: 1px">
                    <span>行政执法人员：</span>
                    <InvestigatorSelect class="InvestigatorSelectReplace"
                        style="height: 6mm; width: calc(9 * 5mm);margin-bottom: 4px;border-bottom: 1px solid black"
                        v-model="form.a3" :id-field="'a4'" @change="handleInvestigatorChange" />
                    <span>行政执法证号：</span>
                    <input v-model="form.a4" :resize="'none'" autosize class="inputStyle1" readonly
                        style="width: calc(9 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea" ref="inputRef6">
                </div>
                <div class="writ-height" style="margin-bottom: 1px">
                    <span>行政执法人员：</span>
                    <InvestigatorSelect class="InvestigatorSelectReplace"
                        style="height: 6mm; width: calc(9 * 5mm);margin-bottom: 4px;border-bottom: 1px solid black"
                        v-model="form.a5" :id-field="'a6'" @change="handleInvestigatorChange" />
                    <span>行政执法证号：</span>
                    <input v-model="form.a6" :resize="'none'" autosize class="inputStyle1" readonly
                        style="width: calc(9 * 5mm);font-family: 仿宋;font-size: 5mm;" type="textarea" ref="inputRef6">
                </div>
                <div class="writ-height">
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;一、被检查（勘验）人基本情况</span>
                </div>
                <div class="writ-height">
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;被检查（勘验）人名称：</span>
                    <privy-info-select-return-array v-model="form.unitName" :isTable="false" :rowConfig="unitNameConfig"
                        return-fields="A" :return-array-template="[
                            { name: 'companyLicense', field: 'B' },
                        ]" @select="selectUnitUpdateData">
                    </privy-info-select-return-array>
                </div>
                <div class="writ-height">
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;统一社会信用代码：</span>
                    <CrossRowInput v-model:value="form.companyLicense" :line-config="companyLicenseConfig">
                    </CrossRowInput>
                </div>
                <div style="height: 100px; line-height: 30px;">
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;通知相关人员到场情况：</span>
                    <CrossRowInput v-model:value="form.a17" :line-config="a17Config"></CrossRowInput>
                </div>
                <div class="writ-height">
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;二、告知事项</span>
                </div>
                <div style="line-height: 30px;">
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;行政执法人员：您好！我们是</span>
                    <CrossRowInput v-model:value="form.a18" :line-config="a18Config"></CrossRowInput>
                    <span>的行政执法人员，这是我们的行政执法证件（出示行政执法证件），请您确认。</span>
                </div>
                <div style="line-height: 30px;">
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;被检查（勘验）人：<input type="checkbox" v-model="form.a14">已确认/<input
                            type="checkbox" v-model="form.a15">不确认</span>
                </div>
                <div style="height: 150px; line-height: 30px;">
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;行政执法人员：现依法就</span>
                    <CrossRowInput v-model:value="form.a19" :line-config="a19Config"></CrossRowInput>
                    <span>进行现场检查（勘验），请协助做好检查（勘验）。针对检查（勘验）中的有关情况，您有权进行陈述和申辩。（有音像记录的，应当告知音像记录的情况）</span>
                </div>
                <div class="writ-height">
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;三、现场检查（勘验）情况</span>
                </div>
                <div style="height: 62px; width: 162mm;">
                    <el-input type="textarea" v-model="form.v1" :rows="v1Config.maxLines"
                        @keydown.native="handleKeyDown('v1', $event)" @input="handleInput('v1', $event)"
                        @paste.native="handlePaste('v1', $event)" class="el-textarea-hidden"
                        style=" height: 100%;white-space: pre;overflow-x: auto;font-family: monospace;" wrap="soft" />
                </div>
                <div style="height: 120px; position: relative;">
                    <div
                        style="position: absolute; bottom: 80px; left: 0px; right: 20px; display: flex; justify-content: space-between; align-items: flex-end;">
                        <div style="display: flex; align-items: flex-end;">
                            被检查（勘验）人：
                            <span style="border-bottom: 1px solid black; padding-bottom: 6px;">
                                <SignatureField label="签名1" sign-type="sign1" :img-url="form.img1"
                                    @update:imgUrl="form.img1 = $event" />
                            </span>
                        </div>
                        <div>
                            <editable-textarea :text="form.date2" param-type="YYYYMMDD2"
                                @send-to-parent="receiveFromChild"></editable-textarea>
                        </div>
                    </div>
                    <div
                        style="position: absolute; bottom: 40px; left: 0px; right: 20px; display: flex; justify-content: space-between; align-items: flex-end; ">
                        <div style="display: flex; align-items: flex-end;">
                            行政执法人员：
                            <span style="border-bottom: 1px solid black; padding-bottom: 6px;">
                                <SignatureField label="签名2" sign-type="sign2" :img-url="form.img2"
                                    @update:imgUrl="form.img2 = $event" />
                            </span>

                        </div>
                        <div>
                            <editable-textarea :text="form.date3" param-type="YYYYMMDD3"
                                @send-to-parent="receiveFromChild"></editable-textarea>
                        </div>
                    </div>
                    <div
                        style="position: absolute; bottom: 0px; left: 0px; right: 20px; display: flex; justify-content: space-between; align-items: flex-end; ">
                        <div style="display: flex; align-items: flex-end;">
                            行政执法人员：
                            <span style="border-bottom: 1px solid black; padding-bottom: 6px;">
                                <SignatureField label="签名3" sign-type="sign3" :img-url="form.img3"
                                    @update:imgUrl="form.img3 = $event" />
                            </span>
                        </div>
                        <div>
                            <editable-textarea :text="form.date4" param-type="YYYYMMDD4"
                                @send-to-parent="receiveFromChild"></editable-textarea>
                        </div>
                    </div>
                </div>
                <div class="page-number-div">
                    第1页/共{{ form.continuationSheet.length + 2 }}页
                </div>
            </div>
            <div v-for="(item, index) in form.continuationSheet" :key="index" class="page-break">
                <div class="title">
                    <div class="biaotididian">现场检查（勘验）笔录（续页）</div>
                </div>
                <div class="tableStyle1">
                    <!-- 黑色条 -->
                    <div style="background: #000;width: 162mm; height: 5px;"></div>
                    <div style="height: 760px; width: 162mm;">
                        <el-input type="textarea" v-model="item.v2" :rows="v2Config[index].maxLines"
                            @keydown.native="continuationSheetHandleKeyDown('v2-' + index, $event)"
                            @input="continuationSheetHandleInput('v2-' + index, $event)"
                            @paste.native="continuationSheetHandlePaste('v2-' + index, $event)"
                            class="el-textarea-hidden"
                            style=" height: 100%;white-space: pre;overflow-x: auto;font-family: monospace;"
                            wrap="soft" />
                    </div>
                    <div style="height: 120px; position: relative;">
                        <div
                            style="position: absolute; bottom: 80px; left: 0px; right: 20px; display: flex; justify-content: space-between; align-items: flex-end;">
                            <div style="display: flex; align-items: flex-end;">
                                被检查（勘验）人：
                                <span style="border-bottom: 1px solid black; padding-bottom: 6px;">
                                    <SignatureField label="签名1" sign-type="sign1" :img-url="item.img1"
                                        @update:imgUrl="item.img1 = $event" />
                                </span>
                            </div>
                            <div>
                                <editable-textarea :text="item.date2" param-type="YYYYMMDD2"
                                    @send-to-parent="(data, type) => receiveFromChildInFor(data, type, index)"></editable-textarea>
                            </div>
                        </div>
                        <div
                            style="position: absolute; bottom: 40px; left: 0px; right: 20px; display: flex; justify-content: space-between; align-items: flex-end; ">
                            <div style="display: flex; align-items: flex-end;">
                                行政执法人员：
                                <span style="border-bottom: 1px solid black; padding-bottom: 6px;">
                                    <SignatureField label="签名2" sign-type="sign2" :img-url="item.img2"
                                        @update:imgUrl="item.img2 = $event" />
                                </span>

                            </div>
                            <div>
                                <editable-textarea :text="item.date3" param-type="YYYYMMDD3"
                                    @send-to-parent="(data, type) => receiveFromChildInFor(data, type, index)"></editable-textarea>
                            </div>
                        </div>
                        <div
                            style="position: absolute; bottom: 0px; left: 0px; right: 20px; display: flex; justify-content: space-between; align-items: flex-end; ">
                            <div style="display: flex; align-items: flex-end;">
                                行政执法人员：
                                <span style="border-bottom: 1px solid black; padding-bottom: 6px;">
                                    <SignatureField label="签名3" sign-type="sign3" :img-url="item.img3"
                                        @update:imgUrl="item.img3 = $event" />
                                </span>
                            </div>
                            <div>
                                <editable-textarea :text="item.date4" param-type="YYYYMMDD4"
                                    @send-to-parent="(data, type) => receiveFromChildInFor(data, type, index)"></editable-textarea>
                            </div>
                        </div>
                    </div>
                    <div class="page-number-div">
                        第{{ index + 2 }}页/共{{ form.continuationSheet.length + 2 }}页
                    </div>
                </div>
            </div>
            <div class="page-break">
                <div class="title">
                    <div class="biaotididian">现场检查（勘验）笔录（续页）</div>
                </div>
                <div class="tableStyle1">
                    <!-- 黑色条 -->
                    <div style="background: #000;width: 162mm; height: 5px;"></div>
                    <div style="height: 607px; width: 162mm;">
                        <el-input type="textarea" v-model="form.v3" :rows="v3Config.maxLines"
                            @keydown.native="handleKeyDown('v3', $event)" @input="handleInput('v3', $event)"
                            @paste.native="handlePaste('v3', $event)" class="el-textarea-hidden"
                            style=" height: 100%;white-space: pre;overflow-x: auto;font-family: monospace;"
                            wrap="soft" />
                    </div>
                    <div style="height: 260px; position: relative;">
                        <div class="writ-height">
                            <span>&nbsp;&nbsp;&nbsp;&nbsp;四、陈述申辩情况</span>
                        </div>
                        <div class="writ-height">
                            <span>&nbsp;&nbsp;&nbsp;&nbsp;</span><input type="checkbox" v-model="form.a16">无
                        </div>
                        <div class="writ-height">
                            <span>&nbsp;&nbsp;&nbsp;&nbsp;</span><input type="checkbox" v-model="form.a13">有
                        </div>
                        <div class="writ-height">
                            <span>&nbsp;&nbsp;&nbsp;&nbsp;行政执法人员：以上是本次检查（勘验）记录，核对无误后请签名或者盖章。</span>
                        </div>
                        <div
                            style="position: absolute; bottom: 80px; left: 0px; right: 20px; display: flex; justify-content: space-between; align-items: flex-end;">
                            <div style="display: flex; align-items: flex-end;">
                                被检查（勘验）人：
                                <span style="border-bottom: 1px solid black; padding-bottom: 6px;">
                                    <SignatureField label="签名4" sign-type="sign4" :img-url="form.img4"
                                        @update:imgUrl="form.img4 = $event" />
                                </span>
                            </div>
                            <div>
                                <editable-textarea :text="form.date5" param-type="YYYYMMDD5"
                                    @send-to-parent="receiveFromChild"></editable-textarea>
                            </div>
                        </div>
                        <div
                            style="position: absolute; bottom: 40px; left: 0px; right: 20px; display: flex; justify-content: space-between; align-items: flex-end; ">
                            <div style="display: flex; align-items: flex-end;">
                                行政执法人员：
                                <span style="border-bottom: 1px solid black; padding-bottom: 6px;">
                                    <SignatureField label="签名5" sign-type="sign5" :img-url="form.img5"
                                        @update:imgUrl="form.img5 = $event" />
                                </span>

                            </div>
                            <div>
                                <editable-textarea :text="form.date6" param-type="YYYYMMDD6"
                                    @send-to-parent="receiveFromChild"></editable-textarea>
                            </div>
                        </div>
                        <div
                            style="position: absolute; bottom: 0px; left: 0px; right: 20px; display: flex; justify-content: space-between; align-items: flex-end; ">
                            <div style="display: flex; align-items: flex-end;">
                                行政执法人员：
                                <span style="border-bottom: 1px solid black; padding-bottom: 6px;">
                                    <SignatureField label="签名6" sign-type="sign6" :img-url="form.img6"
                                        @update:imgUrl="form.img6 = $event" />
                                </span>
                            </div>
                            <div>
                                <editable-textarea :text="form.date7" param-type="YYYYMMDD7"
                                    @send-to-parent="receiveFromChild"></editable-textarea>
                            </div>
                        </div>
                    </div>
                    <div class="page-number-div">
                        第{{ form.continuationSheet.length + 2 }}页/共{{ form.continuationSheet.length + 2 }}页
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import EditableTextarea from "@/views/template/EditableTextarea";
import { agencyName, sealName } from "../../utils/publicName.js"
import PrivyInfoSelectReturnArray from "@/views/template/PrivyInfoSelectReturnArray";
import InvestigatorSelect from "@/views/template/InvestigatorSelect";
import CrossRowInput from "@/views/template/CrossRowInput";
import SignatureField from "@/views/template/SignatureField";
import { createInputLimiter } from '@/utils/limitInput';


export default {
    components: {
        EditableTextarea,
        InvestigatorSelect,
        CrossRowInput,
        SignatureField,
        PrivyInfoSelectReturnArray,
    },

    data() {
        return {
            agencyName: agencyName,
            sealName: sealName,
            form: {
                continuationSheet: [],
            },
            status: '', //当前文书的状态
            isPdfExport: false, //控制打印样式
            unitNameConfig: {
                firstLine: { chars: 19 * 2 },
                middleLines: { count: 0, chars: 32 * 2 },
                lastLine: { chars: 0 * 2 }
            },
            companyLicenseConfig: {
                firstLine: { chars: 21 * 2 },
                middleLines: { count: 0, chars: 32 * 2 },
                lastLine: { chars: 0 * 2 }
            },
            a17Config: {
                firstLine: { chars: 19 * 2 },
                middleLines: { count: 1, chars: 32 * 2 },
                lastLine: { chars: 32 * 2 }
            },
            a18Config: {
                firstLine: { chars: 17 * 2 },
                middleLines: { count: 0, chars: 32 * 2 },
                lastLine: { chars: 8 * 2 }
            },
            a19Config: {
                firstLine: { chars: 19 * 2 },
                middleLines: { count: 0, chars: 32 * 2 },
                lastLine: { chars: 32 * 2 }
            },
            v1Config: {
                maxLines: 2,
                charsPerLine: 32 * 2,
                maxLength: 2 * 32 * 2,
                inputLimiter: null,
                displayText: ''
            },
            v2Config: [],
            v3Config: {
                maxLines: 20,
                charsPerLine: 32 * 2,
                maxLength: 20 * 32 * 2,
                inputLimiter: null,
                displayText: ''
            },
        }
    },

    created() {
        window.parent.getTemplateData((data, status) => {
            this.form = data;
            this.status = status;
            for (let i = 0; i < this.form.continuationSheet.length; i++) {
                this.v2Config.push({
                    maxLines: 25,
                    charsPerLine: 32 * 2,
                    maxLength: 25 * 32 * 2,
                    inputLimiter: null,
                    displayText: ''
                })
                this.v2Config[i].inputLimiter = createInputLimiter(this, {
                    maxLines: this.v2Config[i].maxLines,
                    charsPerLine: this.v2Config[i].charsPerLine,
                    maxLength: this.v2Config[i].maxLength,
                    propName: `form.continuationSheet[${i}].v2`
                });
            }
        })
        window.postForm = () => {
            this.postForm();
        }
        this.v1Config.inputLimiter = createInputLimiter(this, {
            maxLines: this.v1Config.maxLines,
            charsPerLine: this.v1Config.charsPerLine,
            maxLength: this.v1Config.maxLength,
            propName: `form.v1`
        });
        this.v3Config.inputLimiter = createInputLimiter(this, {
            maxLines: this.v3Config.maxLines,
            charsPerLine: this.v3Config.charsPerLine,
            maxLength: this.v3Config.maxLength,
            propName: `form.v3`
        });
    },

    mounted() {
        window.parent.changeTemplateDow();
    },

    methods: {
        // 按字节长度截取字符串（中英文混合）
        subStringByMaxBytes(str, maxBytes, maxRow) {
            if (!str || maxBytes <= 0) return '';

            let bytesCount = 0;
            let result = '';
            let rowCount = 0;

            for (let i = 0; i < str.length; i++) {
                const char = str.charAt(i);
                const charCode = str.charCodeAt(i);

                // 计算当前字符的字节数（中文2字节，其他1字节）
                const charBytes = charCode > 127 ? 2 : 1;

                // 检查是否超过最大字节限制
                if (bytesCount + charBytes > maxBytes) {
                    break;
                }

                // 忽略换行符，直接跳过不计算
                if (char === '\n') {
                    rowCount++;
                    if (rowCount >= maxRow) {
                        break;
                    }
                    result += char;
                    continue;
                }

                bytesCount += charBytes;
                result += char;
            }

            return result;
        },
        // 添加页
        addForm() {
            this.form.continuationSheet.push({
                v2: '',
            });
            this.v2Config.push({
                maxLines: 25,
                charsPerLine: 32 * 2,
                maxLength: 25 * 32 * 2,
                inputLimiter: null,
                displayText: ''
            })
            this.v2Config[this.v2Config.length - 1].inputLimiter = createInputLimiter(this, {
                maxLines: this.v2Config[this.v2Config.length - 1].maxLines,
                charsPerLine: this.v2Config[this.v2Config.length - 1].charsPerLine,
                maxLength: this.v2Config[this.v2Config.length - 1].maxLength,
                propName: `form.continuationSheet[${this.v2Config.length - 1}].v2`
            });
            this.form.continuationSheet[this.form.continuationSheet.length - 1].v2 = this.form.v3;
            this.form.v3 = '';
        },
        // 删除页
        deleteForm() {
            if (this.form.continuationSheet.length > 0) {
                let maxLength = this.v3Config.maxLength;
                let maxRow = this.v3Config.maxLines;
                let subString = this.form.continuationSheet[this.form.continuationSheet.length - 1].v2
                this.form.v3 = this.subStringByMaxBytes(subString, maxLength, maxRow);
                this.form.continuationSheet.pop();
                this.v2Config.pop();
            } else {
                // 使用Element UI的提示（确保已引入ElMessage）
                this.$message.warning('无法删除这一页');
            }
        },
        // 首页处理输入
        getConfigName(field) {
            switch (field) {
                case 'v1':
                    return this.v1Config;
                case 'v3':
                    return this.v3Config;
            }
        },
        handleKeyDown(field, e) {
            const config = this.getConfigName(field);
            config.inputLimiter.handleKeyDown(e);
        },
        handleInput(field, value) {
            const config = this.getConfigName(field);
            this.form[field] = config.inputLimiter.handleInput(value);
        },
        handlePaste(field, e) {
            const config = this.getConfigName(field);
            config.inputLimiter.handlePaste(e);
        },
        // 续表处理输入
        continuationSheetGetConfigName(field) {
            // 将field按-拆分
            const parts = field.split('-');
            const index = parts[1];
            switch (field) {
                case 'v2-' + index:
                    return this.v2Config[index];
            }
        },
        continuationSheetHandleKeyDown(field, e) {
            const config = this.continuationSheetGetConfigName(field);
            config.inputLimiter.handleKeyDown(e);
        },
        continuationSheetHandleInput(field, value) {
            const config = this.continuationSheetGetConfigName(field);
            const parts = field.split('-');
            const field1 = parts[0]
            const index = parts[1];

            // form.continuationSheet数组的第index个中的filed1属性
            this.form.continuationSheet[index][field1] = config.inputLimiter.handleInput(value);
        },
        continuationSheetHandlePaste(field, e) {
            const config = this.continuationSheetGetConfigName(field);
            config.inputLimiter.handlePaste(e);
        },

        // 导出为pdf
        exportPDF() {
            this.savePDF()
                .then((blob) => {

                    const blobUrl = URL.createObjectURL(blob);

                    // 先预览
                    const previewWindow = window.open(blobUrl, '_blank');

                    // 自动下载
                    const fileName = `现场检查（勘验）笔录.pdf`;
                    const downloadLink = document.createElement('a');
                    downloadLink.href = blobUrl;
                    downloadLink.download = fileName;
                    document.body.appendChild(downloadLink);
                    downloadLink.click();
                    document.body.removeChild(downloadLink);

                    // 监听预览窗口关闭后释放内存
                    if (previewWindow) {
                        const timer = setInterval(() => {
                            if (previewWindow.closed) {
                                clearInterval(timer);
                                URL.revokeObjectURL(blobUrl);
                            }
                        }, 1000);
                    } else {
                        setTimeout(() => URL.revokeObjectURL(blobUrl), 10000); // 兜底释放
                    }
                })
                .catch(error => {
                    console.error('导出PDF出错:', error);
                    alert('导出失败，请重试或联系管理员');
                });
        },
        savePDF() {
            this.isPdfExport = true; // 激活PDF样式
            return new Promise((resolve, reject) => {
                this.$nextTick(() => {
                    import('html2pdf.js').then((module) => {
                        const html2pdf = module.default;

                        //获取所有需要替换的 el-input
                        const elInputs = document.querySelectorAll('.el-textarea-hidden .el-input__inner, .el-textarea-hidden .el-textarea__inner');

                        //存储原始元素和它们的父节点，方便后续恢复
                        const originalElements = [];

                        elInputs.forEach((input) => {
                            const div = document.createElement('div');
                            div.style.whiteSpace = 'pre-wrap'; // 保留换行
                            div.style.fontFamily = '仿宋';
                            div.style.fontSize = '19px';
                            div.style.height = '100%';
                            div.style.width = '100%';

                            div.textContent = input.value; // 保留原内容（自动处理 \n 换行）
                            div.style.lineHeight = '30px';
                            div.style.backgroundImage = 'linear-gradient(to top, #000 1px, transparent 1px)';
                            div.style.backgroundSize = '100% 30px';
                            div.style.backgroundRepeat = 'repeat-y';
                            div.style.backgroundPosition = '0 -3px';
                            div.style.padding = '0';
                            div.style.boxSizing = 'border-box';


                            // 替换 el-input，并存储原始元素
                            originalElements.push({
                                parent: input.parentNode,
                                original: input,
                                replacement: div,
                            });
                            input.parentNode.replaceChild(div, input);
                        });

                        // 处理选择执法人的替换
                        const InvestigatorSelectSelects = document.querySelectorAll('.InvestigatorSelectReplace .el-input__inner, .InvestigatorSelectReplace .el-textarea__inner');
                        InvestigatorSelectSelects.forEach((input) => {
                            const div = document.createElement('div');
                            div.style.whiteSpace = 'pre-wrap'; // 保留换行
                            div.style.fontFamily = '仿宋';
                            div.style.fontSize = '5mm';
                            div.textContent = input.value; // 保留原内容（自动处理 \n 换行）
                            div.style.lineHeight = '1.3';

                            // 替换 el-input，并存储原始元素
                            originalElements.push({
                                parent: input.parentNode,
                                original: input,
                                replacement: div,
                            });
                            input.parentNode.replaceChild(div, input);
                        });

                        // 配置选项
                        const opt = {
                            margin: 0,
                            image: {
                                type: 'jpeg',
                                quality: 0.98
                            },
                            html2canvas: {
                                scale: 2,
                                logging: false,
                                useCORS: true
                            },
                            jsPDF: {
                                unit: 'mm',
                                format: 'a4',
                                orientation: 'portrait'
                            }
                        };

                        const element = document.getElementById('pdfDom');

                        // 生成PDF Blob对象
                        html2pdf()
                            .set(opt)
                            .from(element)
                            .toPdf()
                            .get('pdf')
                            .then((pdf) => {
                                const blob = pdf.output('blob');

                                resolve(blob); // 返回Blob对象
                            })
                            .catch((error) => {
                                reject(error);
                            })
                            .finally(() => {
                                this.isPdfExport = false; // 恢复原始样式
                                // 恢复原始input
                                originalElements.forEach(({ parent, original, replacement }) => {
                                    parent.replaceChild(original, replacement);
                                });
                            });
                    }).catch((error) => {
                        reject(error);
                        this.isPdfExport = false;
                        originalElements.forEach(({ parent, original, replacement }) => {
                            parent.replaceChild(original, replacement);
                        });
                    });
                });
            });
        },
        //父页面提交按钮将调用此方法，此方法将文书数据回传到父页面的请求方法中
        postForm() {
            this.savePDF()
                .then((blob) => {


                    // 创建FormData并添加文件
                    const formData = new FormData();
                    formData.append('file', blob, '现场检查（勘验）笔录.pdf');

                    window.parent.postTemplateDate(this.form, formData);
                })
                .catch(error => {
                    console.error('整个保存PDF出错:', error);
                });
        },
        //选择日期时间
        receiveFromChild(data, type) {
            const TypeMap = {
                'HH:mm1': 'time1',
                'HH:mm2': 'time2',
                'YYYYMMDD1': 'date1',
                'YYYYMMDD2': 'date2',
                'YYYYMMDD3': 'date3',
                'YYYYMMDD4': 'date4',
                'YYYYMMDD5': 'date5',
                'YYYYMMDD6': 'date6',
                'YYYYMMDD7': 'date7',
            };
            if (TypeMap[type]) {
                this.form[TypeMap[type]] = data;
            }
        },
        // 处理For循环中的时间
        receiveFromChildInFor(data, type, index) {
            const TypeMap = {
                'YYYYMMDD2': 'date2',
                'YYYYMMDD3': 'date3',
                'YYYYMMDD4': 'date4',
                'YYYYMMDD5': 'date5',
            };
            if (TypeMap[type] && this.form.continuationSheet[index]) {
                this.form.continuationSheet[index][TypeMap[type]] = data;
            }
        },
        //选择执法人员
        handleInvestigatorChange({ identificationNumber, idField }) {
            if (idField && identificationNumber) {
                this.form[idField] = identificationNumber;
            }
        },
        // 选择单位
        selectUnitUpdateData(data) {
            data.forEach(item => {
                this.form[item.name] = item.value;
            })
        },
    }
}
</script>

<style scoped>
:deep(.el-button-print .el-button) {
    display: inline-flex !important;
    visibility: visible !important;
    opacity: 1 !important;
    width: auto;
    min-width: 100px;
    height: auto;
    padding: 8px 15px;
    background: #fff !important;
    color: #000 !important;
    border: none;
}

:deep(.el-textarea__inner) {
    box-shadow: 0 0 0 0;
    color: black;
    padding: 0;
    font-family: "仿宋", serif;
    font-size: 5mm;
    overflow-y: hidden;
    line-height: 1.6;

    /* 下划线 */
    border-radius: 0px;
    background-image: linear-gradient(to top, #000000 0.5px, transparent 1px);
    background-size: 100% 1.6em;
    background-position: 0 -3px;
}

:deep(.el-textarea-hidden .el-textarea__inner) {
    box-shadow: 0 0 0 0;
    color: black;
    padding: 0;
    font-family: "仿宋", serif;
    font-size: 5mm;
    overflow-y: hidden !important;
    resize: none !important;
    height: auto !important;
}

:deep(.el-select .el-input__inner) {
    text-align: center;
    height: 5mm;
}

.input-container {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
}

.inputStyleNoLine {
    border: none;
    outline: none;
    padding: 0px;
}

.typeSpan {
    cursor: pointer;
    font-size: 5mm;
}

/* 完全移除选择框的所有边框和阴影 */
.already-know-select {
    border-bottom: 1px solid #000;
    width: 300px;
    margin: 0;
    padding: 0;
}

:deep(.already-know-select .el-input__wrapper) {
    box-shadow: none !important;
    border: none !important;
    padding: 0px !important;

}

/* 处理聚焦状态 */
:deep(.already-know-select .el-input__wrapper:focus-within) {
    box-shadow: none !important;
    border: none !important;
}

:deep(.already-know-select .el-input__inner) {
    border: none !important;
    outline: none !important;
    box-shadow: none !important;
    font-family: "仿宋", "FangSong", serif !important;
    font-size: 18px !important;
    padding: 0 0px !important;
    color: black !important;
    background-color: transparent !important;
    height: auto !important;
    line-height: 24px !important;
    text-align: left !important;
}

/* 移除提示语 */
:deep(.already-know-select .el-input__inner::placeholder) {
    color: transparent !important;
}

/* 移除下拉箭头 */
:deep(.already-know-select .el-input__suffix) {
    display: none !important;
}

/* 移除聚焦状态下的边框 */
:deep(.already-know-select .el-input__inner:focus) {
    border: none !important;
    box-shadow: 0 0 0 0 !important;
}

/* 下拉面板样式 */
.inspector-popper {
    border: none !important;
    box-shadow: none !important;
    font-family: "仿宋", "FangSong", serif !important;
    font-size: 5mm !important;
}

/* 下拉选项样式 */
:deep(.inspector-popper .el-select-dropdown__item) {
    font-family: "仿宋", "FangSong", serif !important;
    font-size: 5mm !important;
    height: auto !important;
    padding: 5px 10px !important;
}

/* 选中项样式 */
:deep(.inspector-popper .el-select-dropdown__item.selected) {
    color: #000 !important;
    font-weight: normal !important;
    background-color: #f5f5f5 !important;
}
</style>
